package link_list

// https://leetcode.cn/problems/reverse-nodes-in-k-group leetcode-25
func reverseKGroup(head *ListNode, k int) *ListNode {
	if k == 1 || head == nil || head.Next == nil {
		return head
	}
	var start, end, next, prev *ListNode
	dummyNode := &ListNode{Next: head}
	prev = dummyNode

	count := 1
	for node := head; node != nil; {
		if count == 1 {
			start = node
		}

		if count == k {
			end = node
			next = end.Next
			reverse(start, count)
			prev.Next = end
			start.Next = next
			prev = start
			node = next
			count = 1
		} else {
			node = node.Next
			count++
		}
	}
	return dummyNode.Next
}

func reverse(head *ListNode, count int) *ListNode {
	var newHead *ListNode
	for count > 0 {
		tmp := head.Next
		head.Next = newHead
		newHead = head
		head = tmp
		count--
	}
	return newHead
}
